const CracoLessPlugin = require('craco-less');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const path = require('path');

const { REACT_APP_BUILD_ANALYZE } = process.env;

const isPro = (dev) => dev === 'production';

const webpackConfigFun = (webpackConfig, env) => {
  // 配置打包依赖插件分析webpack-bundle-analyzer
  if (isPro(env)) {
    if (REACT_APP_BUILD_ANALYZE === 'analyze') {
      webpackConfig.plugins.push(new BundleAnalyzerPlugin());
    }
    webpackConfig.devtool = false;
  }
  // 配置路径别名
  const { src } = webpackConfig.resolve.alias;

  webpackConfig.resolve.alias = Object.assign(webpackConfig.resolve.alias, {
    '@': src,
    '@components': path.resolve(src, 'components')
  });

  // 配置chunk分割
  webpackConfig.optimization = {
    splitChunks: {
      chunks: 'all',
      maxAsyncRequests: 5, // 按需加载时最大并行请求数
      maxInitialRequests: 4, // 首页渲染时最大并行请求数
      minChunks: 1, // 只要共享1个chunk的模块就可以进行拆分
      minSize: 20000, // 分离出的chunk的最小size
      cacheGroups: {
        icon: {
          name: 'chunk-icon',
          chunks: 'all',
          minChunks: 1,
          minSize: 20000,
          maxAsyncRequests: 5, // 按需加载时最大并行请求数
          maxInitialRequests: 4, // 首页渲染时最大并行请求数
          // eslint-disable-next-line max-len
          test: /[\\/]node_modules[\\/](@ant-design|antd-mobile)[\\/]/,
          priority: -9
        },
        antd: {
          name: 'chunk-antd',
          chunks: 'all',
          minChunks: 1,
          minSize: 20000,
          maxAsyncRequests: 5, // 按需加载时最大并行请求数
          maxInitialRequests: 4, // 首页渲染时最大并行请求数
          test: /[\\/]node_modules[\\/](antd)[\\/]/,
          priority: -8
        },
      }
    }
  };
  return webpackConfig;
};

module.exports = {
  // 配置UI包按需加载
  babel: {
    plugins: [
      [
        '@babel/plugin-transform-react-jsx',
        {
          runtime: 'automatic',
        },
        'plugin-transform-react-jsx'
      ],
      ['import',
        {
          libraryName: 'antd',
          style: true
        },
        'antd'],
    ]
  },
  plugins: [
    {
      plugin: CracoLessPlugin,
      options: {
        lessLoaderOptions: {
          lessOptions: {
            modifyVars: {},
            javascriptEnabled: true,
          },
        }
      }
    },
  ],
  webpack: {
    configure: (webpackConfig, { env }) => webpackConfigFun(webpackConfig, env)
  },
};
